package bank;

import java.util.HashSet;
import java.util.Set;

public class _36IsValidSudoku {
    public static boolean isValidSudoku(char[][] board) {
        //  分别对行、列、方格中的元素进行检测
        for (int i = 0;i < board.length;i++){
            Set<Character> set1 = new HashSet<>(9);
            Set<Character> set2 = new HashSet<>(9);
            Set<Character> set3 = new HashSet<>(9);
            for (int j = 0;j < board[i].length;j++){
                //  在当前元素不为 '.' 且 哈希表添加元素失败时，返回 false
                if (board[i][j] != '.' && !set1.add(board[i][j])){
                    return false;
                }
                if (board[j][i] != '.' && !set2.add(board[j][i])){
                    return false;
                }
                /**
                 * 重点：0,1,2,3,4,5,6,7,8 数组下标变换
                 * 经过 /3*3 ==> 0,0,0,3,3,3,6,6,6 ==>行起始点
                 * 经过 %3*3 ==> 0,3,6,0,3,6,0,3,6 ==>列起始点
                 */
                int a = i / 3 * 3 + j / 3;
                int b = i % 3 * 3 + j % 3;
                if (board[a][b] != '.' && !set3.add(board[a][b])){
                    return false;
                }
            }
        }
        return true;
    }
}
